﻿<%@ WebHandler Language="C#" Class="ZSTempMaterialRequestHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

//Description:临时领料提请处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:longb
//create Date:2023-03-02
public class ZSTempMaterialRequestHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "saveTempMaterialRequestData"://保存临时领料提请信息
                    saveTempMaterialRequestData(context);
                    break;
                case "getTempMaterialRequestData"://查询临时领料提请信息
                    getTempMaterialRequestData(context);
                    break;
                case "getTempMaterialRequestDataByPageSize"://查询临时领料提请信息(分页)
                    getTempMaterialRequestDataByPageSize(context);
                    break;
                case "updateTempMaterialRequestData"://更新临时领料提请信息
                    updateTempMaterialRequestData(context);
                    break;
                case "deleteTempMaterialRequestData"://删除临时领料提请信息
                    deleteTempMaterialRequestData(context);
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 保存临时领料提请信息
    /// </summary>
    /// <param name="context"></param>
    public void saveTempMaterialRequestData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var TMRType = context.Request["TMRType"].ToString();
        var mfgOrderID = context.Request["mfgOrderID"].ToString();
        var sqlArr = new ArrayList();
        var dtCount = DatabaseHelper.Query_ReturnDatTable("select COUNT(distinct ZSTempMaterialRequestNO)+1 C From ZSTempMaterialRequest");
        var strSequence = "000000" + (dtCount.Rows.Count == 0 || dtCount.Rows[0]["C"].ToString() == "0" ? "1" : dtCount.Rows[0]["C"].ToString());
        var BillNo = "LSLLTQ-" + DateTime.Now.ToString("yyyy") + "-" + m_UserInfo.FactoryCode + "-" + strSequence.Substring(strSequence.Length - 4);
        var insertSQL = @"insert into ZSTempMaterialRequest(ZSTempMaterialRequestID,ZSTempMaterialRequestNO,TMRType,MFGORDERID,PRODUCTID,ApplyNum,TMRReason,CREATEDATE,CREATEEMPLOYEEID,STATUS)
                        VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}',sysdate,'{7}','0')";
        foreach (DataRow row in dt.Rows)
        {
            if (!string.IsNullOrWhiteSpace(row["ApplyNum"].ToString()))
            {
                var GID = Guid.NewGuid().ToString();
                sqlArr.Add(string.Format(insertSQL, GID, BillNo, TMRType, mfgOrderID, row["PRODUCTID"], row["ApplyNum"], row["TMRReason"], m_UserInfo.EmployeeID));
            }
        }
        if (sqlArr.Count > 0)
        {
            result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        }
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询临时领料提请信息
    /// </summary>
    public void getTempMaterialRequestDataByPageSize(HttpContext context)
    {
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var SelSQL = GetTempMaterialRequestzSql(context);
        if (!string.IsNullOrWhiteSpace(dic["Machine"].ToString()))
        {
            SelSQL += " and u.ATTRIBUTEVALUE like '%" + dic["Machine"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["MfgOrdername"].ToString()))
        {
            SelSQL += " and m.MFGORDERNAME like '%" + dic["MfgOrdername"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["billname"].ToString()))
        {
            SelSQL += " and sr.ZSTempMaterialRequestNO like '%" + dic["billname"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["status"].ToString()))
        {
            SelSQL += " and (CASE WHEN nvl(sr.ApplyNum,0)-nvl(sr.USENUM,0)=0 THEN 4 WHEN nvl(sr.USENUM,0)<nvl(sr.ApplyNum,0) AND nvl(sr.USENUM,0)>0 THEN 3 ELSE sr.STATUS END)= '" + dic["status"].ToString() + "'";
        }

        if (!string.IsNullOrWhiteSpace(dic["startdate"].ToString()))
        {
            SelSQL += " and to_char(sr.CREATEDATE,'yyyy-MM-dd hh24:mi:ss')>= '" + dic["startdate"].ToString() + "'";
        }
        if (!string.IsNullOrWhiteSpace(dic["enddate"].ToString()))
        {
            SelSQL += " and to_char(sr.CREATEDATE,'yyyy-MM-dd hh24:mi:ss')<= '" + dic["enddate"].ToString() + "'";
        }

        uMESProcessResult result = new uMESProcessResult();
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = SelSQL;
        result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public void getTempMaterialRequestData(HttpContext context)
    {
        var SelSQL = GetTempMaterialRequestzSql(context);
        if (!string.IsNullOrWhiteSpace(context.Request["mfgOrderID"].ToString()))
        {
            SelSQL += " AND sr.mfgOrderID='" + context.Request["mfgOrderID"].ToString() + "'";
        }
        var dt = DatabaseHelper.Query_ReturnDatTable(SelSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }

    public string GetTempMaterialRequestzSql(HttpContext context)
    {
        var SelSQL = @"SELECT sr.ZSTempMaterialRequestID,sr.ZSTempMaterialRequestNO,sr.TMRType,m.MFGORDERNAME,u.ATTRIBUTEVALUE MachineNO
            ,P2.PRODUCTNAME,P.DESCRIPTION PRODUCTDESCRIPTION,sr.ApplyNum,nvl(sr.USENUM,0) USENUM,nvl(t.ERFMG,0)-nvl(sr.USENUM,0) NOUSENUM,sr.TMRReason
            ,CASE WHEN nvl(sr.ApplyNum,0)-nvl(sr.USENUM,0)=0 THEN 4 WHEN nvl(sr.USENUM,0)<nvl(sr.ApplyNum,0) AND nvl(sr.USENUM,0)>0 THEN 3 ELSE sr.STATUS END  STATUS
            ,to_char(sr.CREATEDATE,'yyyy-MM-dd hh24:mi:ss')CREATEDATE,e.FullNAME CREATEDATENAME
            ,to_char(sr.SUBMITDATE,'yyyy-MM-dd hh24:mi:ss')SUBMITDATE,e2.FullNAME SUBMITNAME
            ,to_char(sr.CONFIRMDATE,'yyyy-MM-dd hh24:mi:ss')CONFIRMDATE,e3.FullNAME CONFIRMNAME
            ,to_char(sr.TMRUseDate,'yyyy-MM-dd hh24:mi:ss')TMRUseDate,e4.FullNAME TMRUSENAME
            ,sr.ERPTMRNO,nvl(t.ERFMG,0) ERFMG
            FROM ZSTempMaterialRequest sr
            LEFT JOIN MFGORDER m ON m.MFGORDERID =sr.MFGORDERID
            LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
            LEFT JOIN PRODUCT p ON p.PRODUCTID =sr.PRODUCTID
            LEFT JOIN PRODUCTBASE p2 ON p2.PRODUCTBASEID =p.PRODUCTBASEID 
            LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =sr.CREATEEMPLOYEEID
            LEFT JOIN EMPLOYEE e2 ON e2.EMPLOYEEID =sr.SUBMITEMPLOYEEID
            LEFT JOIN EMPLOYEE e3 ON e3.EMPLOYEEID =sr.CONFIRMEMPLOYEEID
            LEFT JOIN EMPLOYEE e4 ON e4.EMPLOYEEID =sr.TMRUseEmployeeID
            LEFT JOIN T_LSLLTQ t ON t.ZACODE=sr.ERPTMRNO AND DECODE(sr.TMRType,'0','SCTL|生产退料','1','BFFL|补废领料')=t.ATYPE 
            WHERE nvl(sr.isuse,0)=0  ";
        return SelSQL;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void updateTempMaterialRequestData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var type = context.Request["type"].ToString();
        var sqlArr = new ArrayList();
        var tipText = "提交";
        var updateSQL = @"Update ZSTempMaterialRequest set status=1,SUBMITDATE=sysdate,SUBMITEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where ZSTempMaterialRequestID='{0}'";
        if (type == "confirm") { updateSQL = @"Update ZSTempMaterialRequest set status=2,CONFIRMDATE=sysdate,CONFIRMEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where ZSTempMaterialRequestID='{0}'"; tipText = "确认"; }
        if (type == "return") { updateSQL = @"Update ZSTempMaterialRequest set status=0,CONFIRMDATE=sysdate,CONFIRMEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where ZSTempMaterialRequestID='{0}'"; tipText = "退回"; }
        if (type == "erpno") { updateSQL = @"Update ZSTempMaterialRequest set ERPTMRNO='{0}' where ZSTempMaterialRequestID='{1}'"; tipText = "保存"; }
        if (type == "use") { updateSQL = @"Update ZSTempMaterialRequest set USENUM={0}+nvl(USENUM,0),TMRUseDate=sysdate,TMRUseEmployeeID='" + m_UserInfo.EmployeeID + "' where ZSTempMaterialRequestID='{1}'"; tipText = "保存"; }
        foreach (DataRow row in dt.Rows)
        {
            if (type == "erpno" && row["STATUS"].ToString() == "2")
            {
                sqlArr.Add(string.Format(updateSQL, row["ERPTMRNO"], row["ZSTempMaterialRequestID"]));
            }
            if (type == "use" && row["STATUS"].ToString() == "2" && Convert.ToInt32(row["NOUSENUM"].ToString()) > 0)
            {
                sqlArr.Add(string.Format(updateSQL, Convert.ToInt32(row["NOUSENUM"].ToString()), row["ZSTempMaterialRequestID"]));
            }
            if (type == "confirm" || type == "return" || type == "submit")
            {
                sqlArr.Add(string.Format(updateSQL, row["ZSTempMaterialRequestID"]));
            }
        }
        if (sqlArr.Count > 0)
        {
            result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        }
        result.Message = result.Result ? tipText + "成功" : tipText + "失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void deleteTempMaterialRequestData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var sqlArr = new ArrayList();
        var updateSQL = @"Update ZSTempMaterialRequest set isuse=1 where ZSTempMaterialRequestID='{0}'";
        foreach (DataRow row in dt.Rows)
        {
            sqlArr.Add(string.Format(updateSQL, row["ZSTempMaterialRequestID"]));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        result.Message = result.Result ? "删除成功" : "删除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
}